package com.aounhui.productor.init;

import com.aounhui.common.entity.Message;
import com.aounhui.productor.entity.CommodityFactory;
import com.aounhui.productor.entity.CommodityFactoryExample;
import com.aounhui.productor.mapper.CommodityFactoryMapper;
import com.aounhui.productor.mapper.CommodityMapper;
import com.aounhui.productor.openfeign.MessageServiceFeign;
import com.aounhui.productor.service.CommodityService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.List;

/**
 * @author aounhui
 * @version 1.0
 * @date 2021/6/29 15:16
 * @description 启动服务，检查商品及库存，根据情况发送消息
 */
@Component
@Slf4j
public class CommodityInit {
    @Autowired
    private CommodityService commodityService;
    @Autowired
    private CommodityFactoryMapper factoryMapper;
    @Autowired
    private CommodityMapper commodityMapper;
    @Autowired
    private MessageServiceFeign messageServiceFeign;
    @PostConstruct
    public void commodityInit() {
        log.info("生产者启动，检查每种商品和库存情况");
        List<CommodityFactory> commodityFactories = factoryMapper.selectByExample(new CommodityFactoryExample());
        commodityFactories.forEach(commodityFactory -> {
            //更新库存过期产品。
            int overdue = commodityMapper.updateOverdue();
            log.info("更新过期产品数量{}", overdue);
            boolean satisfyCommodity = commodityService.satisfyCommodity(commodityFactory.getName());
            if (! satisfyCommodity) {
                log.info("调用queue微服务，发送消息");
                Message message = Message.builder().type(commodityFactory.getName())
                        .content("please product " + commodityFactory.getName()).build();
                //其他服务发送消息
                messageServiceFeign.sendMessage(message);
                //自己发送消息
//                sendMessage.sendMessage(commodityFactory.getName(), "please product");
                log.info("{}检查库存量不满足最大存量，发送请求生产消息成功", commodityFactory.getName());
            }
        });

    }

    @Scheduled(cron = "0 0/30 9-18 * * ?")
    public void commodityUpdateSchedule() {
        log.info("朝9晚6：半小时更新库存过期状态定时任务");
        commodityInit();
    }



}
